package boardgamer.yavalath.client.game;

import android.graphics.Canvas;
import boardgamer.common.board.HexagonBoard;
import boardgamer.common.net.PlayerId;
import boardgamer.yavalath.common.YavalathBoard;
import boardgamer.yavalath.common.YavalathTile;
import com.google.common.collect.Lists;
import com.google.common.collect.Table.Cell;

import java.util.Collection;
import java.util.List;


public class YavalathDrawableBoard extends HexagonBoard<YavalathDrawableTile> {

  private static final long serialVersionUID = 1773216869249689929L;
  
  private final List<PlayerId> losers;

  public YavalathDrawableBoard(TileFactory<YavalathDrawableTile> tileFactory,
      YavalathBoard board) {
    super(tileFactory, board.getSide());
    this.losers = Lists.newLinkedList();
  }

  public void update(YavalathBoard board, boolean resetAlpha) {
    for (Cell<Integer, Integer, YavalathTile> cell : board.getBoard().cellSet()) {
      YavalathTile newTile = cell.getValue();
      YavalathDrawableTile drawableTile = findTile(newTile.getX(), newTile.getY());
      if (newTile.hasOwner()) {
        drawableTile.setOwner(newTile.getOwner());
      } else {
        drawableTile.unsetOwner();
      }
      if (resetAlpha) {
        drawableTile.setAlpha(255);
      }
    }
  }

  public void update(YavalathBoard board) {
    update(board, false /* resetAlpha */);
  }

  public void draw(Canvas canvas) {
    for (YavalathDrawableTile tile : getTiles()) {
      // Only draw if the tile either has no owners, or the owner has not lost
      if (!tile.hasOwner() || !losers.contains(tile.getOwner())) {
        tile.render(canvas);
      }
    }
  }

  public void addLoser(PlayerId loser) {
    losers.add(loser);
  }
  
  public void setLosers(Collection<PlayerId> losers) {
    this.losers.clear();
    this.losers.addAll(losers);
  }
}
